/**
 *
 */
package ua.at.tsvetkov.samizdat.adapters;

import java.io.File;
import java.io.FileFilter;
import java.util.Date;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.data.Data;
import ua.at.tsvetkov.samizdat.data.DataDownloader;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AdtGenres extends DataReaderAdapter {

	/**
	 * @param context
	 * @param dataReader
	 */
	public AdtGenres(Activity context, DataDownloader dataLoader, int partSize) {
		super(context, dataLoader, partSize);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = super.getView(position, convertView, parent);
		if (view != null)
			return view;

		GenreViewHolder holder = new GenreViewHolder();
		if (convertView == null || convertView.getTag() != holder) {
			convertView = mInflater.inflate(R.layout.adt_genre, null);
			holder.loaded = (TextView) convertView.findViewById(R.id.AdtGenreLoadedDate);
			holder.text = (TextView) convertView.findViewById(R.id.AdtGenreText);
			holder.count = (TextView) convertView.findViewById(R.id.AdtGenreCount);
			convertView.setTag(holder);
		} else {
			holder = (GenreViewHolder) convertView.getTag();
		}
		String[] genreData = dataLoader.getDataFields(position - 1, Data.GENRE_FIELDS_COUNT);
		File path = new File(Const.FILE_ROOT);
		File[] files = path.listFiles(getFileFilter(".genre_" + genreData[Data.GENRE_CODE]));
		if (files != null && files.length > 0) {
			holder.loaded.setText("Обновлено " + (new Date(files[0].lastModified())).toLocaleString());
		} else {
			holder.loaded.setText("");
		}
		holder.text.setText(genreData[Data.GENRE_TEXT]);
		holder.count.setText(genreData[Data.GENRE_COUNT]);
		return convertView;
	}

	private FileFilter getFileFilter(final String pref) {
		// TODO Auto-generated method stub
		return new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				if (pathname.getName().startsWith(pref))
					return true;
				else
					return false;
			}

		};
	}

	@Override
	public void refreshData() {
		// TODO Auto-generated method stub

	}

}

class GenreViewHolder {
	TextView	loaded;
	TextView	text;
	TextView	count;
}
